'use client';

import { useState, useEffect } from 'react';
import { SqlEditor } from '@/components/SqlEditor';
import { ResultsTable } from '@/components/ResultsTable';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { initDatabase, executeQuery, resetDatabase } from '@/lib/sql-service';
import { scenarios, Scenario, Task } from '@/lib/learning-scenarios';
import { HiCheckCircle, HiQuestionMarkCircle, HiOutlineDotsCircleHorizontal } from 'react-icons/hi';

export default function LearnPage() {
  const [currentScenario, setCurrentScenario] = useState<Scenario>(scenarios[0]);
  const [currentTaskIndex, setCurrentTaskIndex] = useState(0);
  const [results, setResults] = useState<{ columns: string[]; rows: any[] }>({ columns: [], rows: [] });
  const [error, setError] = useState<string | undefined>();
  const [isLoading, setIsLoading] = useState(true);
  const [taskStatus, setTaskStatus] = useState<Record<string, 'completed' | 'pending'>>({});
  const [validationMessage, setValidationMessage] = useState<string | undefined>();

  const currentTask = currentScenario.tasks[currentTaskIndex];

  useEffect(() => {
    const init = async () => {
      setIsLoading(true);
      setError(undefined);

      try {
        console.log('开始初始化学习环境...');
        await initDatabase();
        console.log('数据库初始化成功，开始设置场景...');
        await setupScenario(currentScenario);
        console.log('场景设置成功，应用程序准备就绪');
        setIsLoading(false);
      } catch (err) {
        console.error('初始化失败:', err);
        setError('数据库初始化失败：' + (err instanceof Error ? err.message : String(err)));
        setIsLoading(false);
      }
    };

    init();
  }, [currentScenario]);

  const setupScenario = async (scenario: Scenario) => {
    try {
      // 尝试重置数据库，确保我们有一个干净的起点
      await resetDatabase();
      console.log('数据库已重置，开始执行设置查询...');

      // 执行场景的设置查询
      for (const query of scenario.setupQueries) {
        try {
          await executeQuery(query);
        } catch (error) {
          const errorMessage = String(error);

          // 忽略"表已存在"错误，这是可以接受的
          if (errorMessage.includes('already exists')) {
            console.log('注意：表已存在，继续执行...', errorMessage);
          }
          // 忽略唯一约束错误，这通常意味着数据已存在
          else if (errorMessage.includes('UNIQUE constraint failed')) {
            console.log('注意：唯一约束错误，可能数据已存在，继续执行...', errorMessage);
          }
          // 如果是其他错误则抛出
          else {
            console.error('执行查询时出现未知错误:', errorMessage);
            throw error;
          }
        }
      }

      // 初始化任务状态
      const initialStatus: Record<string, 'completed' | 'pending'> = {};
      scenario.tasks.forEach(task => {
        initialStatus[task.id] = 'pending';
      });
      setTaskStatus(initialStatus);
      console.log('场景设置完成，任务状态已初始化');

    } catch (err) {
      console.error('设置场景失败:', err);
      setError('设置学习场景失败：' + String(err));
      throw err;
    }
  };

  const handleExecute = async (query: string) => {
    setError(undefined);
    setValidationMessage(undefined);

    try {
      const result = await executeQuery(query);
      setResults(result);

      // 验证任务
      if (currentTask.validation) {
        const validation = currentTask.validation(result);
        if (validation.valid) {
          setTaskStatus(prev => ({
            ...prev,
            [currentTask.id]: 'completed'
          }));
          setValidationMessage(validation.message || '任务完成！');
        } else {
          setValidationMessage(validation.message || '任务未完成，请再试一次。');
        }
      }

    } catch (err: any) {
      console.error('查询执行失败:', err);
      setError(err.toString());
      setResults({ columns: [], rows: [] });
    }
  };

  const handleNextTask = () => {
    if (currentTaskIndex < currentScenario.tasks.length - 1) {
      setCurrentTaskIndex(currentTaskIndex + 1);
      setResults({ columns: [], rows: [] });
      setError(undefined);
      setValidationMessage(undefined);
    }
  };

  const handlePrevTask = () => {
    if (currentTaskIndex > 0) {
      setCurrentTaskIndex(currentTaskIndex - 1);
      setResults({ columns: [], rows: [] });
      setError(undefined);
      setValidationMessage(undefined);
    }
  };

  const handleShowSolution = () => {
    // 只显示解决方案，不执行
    if (currentTask.sampleSolution) {
      setValidationMessage(`参考解决方案: ${currentTask.sampleSolution.trim()}`);
    }
  };

  if (isLoading) {
    return <div className="container mx-auto py-10 px-4 text-center">正在加载学习环境...</div>;
  }

  return (
    <div className="container mx-auto py-10 px-4">
      <h1 className="text-3xl font-bold mb-2">{currentScenario.title}</h1>
      <p className="text-muted-foreground mb-6">{currentScenario.description}</p>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2">
          <Card className="mb-6">
            <CardHeader>
              <CardTitle>任务 {currentTaskIndex + 1}: {currentTask.title}</CardTitle>
              <CardDescription>{currentTask.description}</CardDescription>
            </CardHeader>
            <CardContent>
              {currentTask.hint && (
                <div className="bg-muted p-3 rounded-md mb-4 flex items-start">
                  <div className="mr-2 h-5 w-5 text-blue-500 mt-0.5">
                    <HiQuestionMarkCircle size={20} />
                  </div>
                  <div>
                    <p className="font-medium">提示</p>
                    <p className="text-sm">{currentTask.hint}</p>
                  </div>
                </div>
              )}

              {validationMessage && (
                <div className={`p-3 rounded-md mb-4 ${taskStatus[currentTask.id] === 'completed' ? 'bg-green-50' : 'bg-yellow-50'}`}>
                  <p className={taskStatus[currentTask.id] === 'completed' ? 'text-green-700' : 'text-yellow-700'}>
                    {validationMessage}
                  </p>
                </div>
              )}

              <div className="flex space-x-2 mb-4">
                <Button
                  variant="outline"
                  onClick={handlePrevTask}
                  disabled={currentTaskIndex === 0}
                >
                  上一个任务
                </Button>
                <Button
                  variant="outline"
                  onClick={handleNextTask}
                  disabled={currentTaskIndex === currentScenario.tasks.length - 1}
                >
                  下一个任务
                </Button>
                <Button
                  variant="outline"
                  onClick={handleShowSolution}
                >
                  查看解决方案
                </Button>
              </div>
            </CardContent>
          </Card>

          <SqlEditor onExecute={handleExecute} />

          <div className="mt-6">
            <ResultsTable
              columns={results.columns}
              rows={results.rows}
              error={error}
            />
          </div>
        </div>

        <div>
          <Card>
            <CardHeader>
              <CardTitle>任务列表</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {currentScenario.tasks.map((task, index) => (
                  <div
                    key={task.id}
                    className={`flex items-center p-2 rounded-md cursor-pointer ${index === currentTaskIndex ? 'bg-muted' : ''
                      }`}
                    onClick={() => setCurrentTaskIndex(index)}
                  >
                    {taskStatus[task.id] === 'completed' ? (
                      <div className="mr-2 h-5 w-5 text-green-500">
                        <HiCheckCircle size={20} />
                      </div>
                    ) : (
                      <div className="mr-2 h-5 w-5 text-gray-300">
                        <HiOutlineDotsCircleHorizontal size={20} />
                      </div>
                    )}
                    <span>{task.title}</span>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>

          <Card className="mt-6">
            <CardHeader>
              <CardTitle>数据库结构</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="border rounded-md p-3">
                  <h3 className="font-medium">users</h3>
                  <pre className="text-xs mt-2 bg-muted p-2 rounded overflow-x-auto">
                    id INTEGER PRIMARY KEY,
                    username TEXT NOT NULL UNIQUE,
                    email TEXT NOT NULL,
                    created_at TIMESTAMP
                  </pre>
                </div>

                <div className="border rounded-md p-3">
                  <h3 className="font-medium">products</h3>
                  <pre className="text-xs mt-2 bg-muted p-2 rounded overflow-x-auto">
                    id INTEGER PRIMARY KEY,
                    name TEXT NOT NULL,
                    description TEXT,
                    price REAL NOT NULL,
                    stock INTEGER NOT NULL
                  </pre>
                </div>

                <div className="border rounded-md p-3">
                  <h3 className="font-medium">orders</h3>
                  <pre className="text-xs mt-2 bg-muted p-2 rounded overflow-x-auto">
                    id INTEGER PRIMARY KEY,
                    user_id INTEGER NOT NULL,
                    order_date TIMESTAMP,
                    status TEXT,
                    FOREIGN KEY (user_id) REFERENCES users(id)
                  </pre>
                </div>

                <div className="border rounded-md p-3">
                  <h3 className="font-medium">order_items</h3>
                  <pre className="text-xs mt-2 bg-muted p-2 rounded overflow-x-auto">
                    id INTEGER PRIMARY KEY,
                    order_id INTEGER NOT NULL,
                    product_id INTEGER NOT NULL,
                    quantity INTEGER NOT NULL,
                    price REAL NOT NULL,
                    FOREIGN KEY (order_id) REFERENCES orders(id),
                    FOREIGN KEY (product_id) REFERENCES products(id)
                  </pre>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
} 